import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { getToken, removeToken } from '@/utils/auth' // 验权
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 60000, // 请求超时时间
  maxContentLength: 20000000
})

service.route_api_path = '/api'

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()// 让每个请求携带自定义token 请根据实际情况自行修改
    console.log(config)
  }
  if (config.method === 'post' || config.method === 'put') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.transformRequest = [function(data) {
      let ret = ''
      for (const it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }]
  }

  return config
}, error => {
  // Do something with request error
  console.log('client request:')
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => response,
  error => {
    console.log('response error:')
    console.log(error.response) // for debug
    let message = ''
    let errcode = 400
    if (error.response && error.response.data) {
      if (error.response.data.code && error.response.data.msg) {
        message = error.response.data.msg
        errcode = error.response.data.code
        // 转换错误提示信息
        switch (errcode) {
          case 403001:
            message = '登入超时，请退出重新登入'
            removeToken()
            break
          case 403003:
            message = '用户名或密码不正确'
            break
          default:
            break
        }
      } else {
        message = error.response.data
      }
    }

    Message({
      message: message,
      showClose: true,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
